package com.example.demo.algorithms;

import io.jsonwebtoken.lang.Assert;

/**
 * <p>Description: 第k个大的元素</p>
 *
 * @author Eric Lee
 * @version v1.0.0
 * @since 2021/2/27 16:15
 **/
public class KthLargest {

    public void test() {
        int[] a = {100, 88, 44, 66, 77, 11, 22, 5, 55};
        int[] result = {100, 88, 66, 77, 55};
        int b = findKthLargest(a, 5);
//        Assert.isTrue(result == b);
        System.out.println(b);
    }

    public int findKthLargest(int[] nums, int k) {
        int heapSize = nums.length;
        buildMaxHeap(nums, heapSize);
        for (int i = nums.length - 1; i >= nums.length - k + 1; --i) {
            swap(nums, 0, i);
            --heapSize;
            maxHeapify(nums, 0, heapSize);
        }
        return nums[0];
    }

    // 构建最大堆
    public void buildMaxHeap(int[] a, int heapSize) {
        for (int i = heapSize / 2; i >= 0; --i) {
            maxHeapify(a, i, heapSize);
        }
    }

    // 维护调整最大堆性质
    public void maxHeapify(int[] a, int i, int heapSize) {
        int l = i * 2 + 1, r = i * 2 + 2, largest = i;
        if (l < heapSize && a[l] > a[largest]) {
            largest = l;
        }
        if (r < heapSize && a[r] > a[largest]) {
            largest = r;
        }
        if (largest != i) {
            swap(a, i, largest);
            maxHeapify(a, largest, heapSize);
        }
    }

    public void swap(int[] a, int i, int j) {
        int temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }

}
